﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace client
{
    public partial class LiveControlDialog : Form
    {
        private Connection connection = new Connection();
        private bool offlineMode = false;

        public LiveControlDialog()
        {
            try
            {
                connection.Connect();
                connection.SendCommand("override 1");
            }
            catch
            {
                offlineMode = true;
            }

            InitializeComponent();

            ledStackPanel3.Visible = ledStackPanel3.Controls.Count > 0;
            LedChannelControl.GroupsChanged += new LedGroupListChanged(LedChannelControl_GroupsChanged);

            foreach (LedChannelControl c in ledStackPanel1.Controls)
            {
                c.Connection = connection;
                c.Initialize();
            }
        }

        void LedChannelControl_GroupsChanged(string[] groups)
        {
            foreach (string s in groups)
            {
                bool found = false;
                foreach (LedGroupControl c in ledStackPanel3.Controls)
                {
                    if (c.Group == s)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                    continue;

                ledStackPanel3.Controls.Add(new LedGroupControl() { Group = s });
            }

            foreach (LedGroupControl c in ledStackPanel3.Controls)
            {
                bool found = false;
                foreach (string s in groups)
                {
                    if (c.Group == s)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                    continue;

                ledStackPanel3.Controls.Remove(c);
            }

            ledStackPanel3.Visible = ledStackPanel3.Controls.Count > 0;
        }

        private void ledStackPanel3_Resize(object sender, EventArgs e)
        {
        }

        private void LiveControlDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (offlineMode)
                return;

            connection.SendCommand("override 0");
            connection.Close();
        }
    }
}
